import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const SchoolSchema = new mongoose.Schema({
    name: String,
    shortName: String,
    logo: String,
    bssName: String,
    colleges: Array,
    majors: Array,
    grades: Array,
    deliveryPlaces: String,
    bbsCategories: String,
    shCategories: String,
});

SchoolSchema.methods.saveSchool = function (school, cb) {
    school.createTime = moment().unix();
    this.model('school').insertMany([school], cb);
};

SchoolSchema.methods.getSchools = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const schoolModel = this.model('school');
    schoolModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        schoolModel.find(leftQuery).skip((current - 1) * pageSize).limit(pageSize).exec((err, schools) => cb(err, schools, count, hasMore));
    });
};

SchoolSchema.methods.getAllSchools = function (query, cb) {
    // this.model('school').find(query, { name: 1, _id: 0 }, cb);
    this.model('school').find(query, cb);
};

SchoolSchema.methods.getSchool = function (query, cb) {
    this.model('school').findOne(query, cb);
};

SchoolSchema.methods.updateSchool = function (school, cb) {
    const _id = school._id;
    delete school._id;
    this.model('school').findOneAndUpdate({ _id }, { $set: school }, cb);
};

SchoolSchema.methods.removeSchools = function (schoolIds, cb) {
    this.model('school').remove({ _id: { $in: schoolIds } }, cb);
};

export default db.model('school', SchoolSchema);